﻿using System;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using SpCop.Core.Model;
using SpCop.Model;

namespace SpCop.General.Modules
{
    class WebPartModulesHaveValidTypes : ModuleRuleBase
    {
        private static XNamespace nsv3 = XNamespace.Get("http://schemas.microsoft.com/WebPart/v3");

        public WebPartModulesHaveValidTypes()
            : base(a => a == "_catalogs/wp")
        {
            
        }

        protected override void VisitModule(Package package, Feature feature, Element item)
        {
                foreach (var file in GetFileElements(item.Xml, ".webpart"))
                {
                    var urlValue = file.Attribute("Url").Value;
                    var path = Path.Combine(Path.Combine(Package.Path, feature.Folder), urlValue);

                    if (!File.Exists(path))
                    {
                        AddProblem("WebPartFileNotFound", feature.Title, urlValue);
                    }
                    else
                    {
                        var wpFile = XDocument.Load(path).Root;

                       
                        if (wpFile != null)
                        {
                            var wpElements = wpFile.Element(nsv3.GetName("webPart"));
                            if (wpElements != null)
                            {
                                var metadata = wpElements.Element(nsv3.GetName("metaData")).Element(nsv3.GetName("type")).Attribute("name").Value;
                                var indexOfComma = metadata.IndexOf(",");
                                var assemblyName = metadata.Substring(indexOfComma + 1).Trim();
                                var typeNmae = metadata.Substring(0, indexOfComma);
                                

                                //try
                                //{
                                //    var wpType = assembly.GetType(nst, typet, true);
                           
                                //}
                                //catch (Exception exception)
                                //{
                                //    AddProblem("WebPartTypeDoesNotExist", feature.Folder, urlValue, metadata, exception.Message);
                                //}
                            }
                        }
                    }
                }

            
        }
    }
}
